<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>数据源绑定</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/libs/layui2.2.5/css/layui.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/common.css">
    <link rel="icon" href="${pageContext.request.contextPath}/static/libs/uiframe/frame/static/image/code.png">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/libs/ol4.5.0/ol.css">
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/libs/ol4.5.0/ol.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/libs/iclient9-openlayers/iclient-openlayers.min-9.0.0-742.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/spatial/js/c3gis_layer.js"></script>
    <style type="text/css">
        .layui-form-item {
            margin-bottom: 10px;
            clear: both;
        }
        .layui-table {
            width: 100%;
            margin: 0px;
            background-color: #fff;
        }
        .layui-table-cell .layui-form-checkbox {
            top: 6px;
        }
        .layui-input-block {
            margin-left: 100px;
            min-height: 36px;
        }
        .layui-table-view {
            position: relative;
            margin: 0px 0;
            overflow: hidden;
        }
        .layui-form-label {
            float: left;
            display: block;
            padding: 9px 10px;
            width: 80px;
            font-weight: 400;
            text-align: right;
        }
    </style>
</head>
<body>
<div class="layui-col-md3">
    <c:choose>
        <c:when test="${type == 'ol.layer.Group'}">

        </c:when>
        <c:when test="${type == 'ol.layer.Tile'}">
            <div class="layui-form-item" style="margin-top: 5px;">
                <label class="layui-form-label">透明度：</label>
                <div class="layui-input-block">
                    <input type="text" name="opacity" value="${opacity}"
                           lay-verify="" autocomplete="off" placeholder="请输入透明度，如：0.8" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">显示范围：</label>
                <div class="layui-input-block">
                    <input type="text" name="extent" value="${extent}"
                           lay-verify="" autocomplete="off" placeholder="请输入显示范围，如：114.229839,33.93893,123.40053,38.904819" class="layui-input">
                </div>
            </div>
        </c:when>
        <c:when test="${type == 'ol.layer.Vector'}">
            <form class="layui-form c3form" action="">
                <!--
                <div class="layui-form-item">
                    <label class="layui-form-label">透明度：</label>
                    <div class="layui-input-block">
                        <input type="text" name="opacity" value="${opacity}"
                               lay-verify="" autocomplete="off" placeholder="请输入透明度，如：0.8" class="layui-input">
                    </div>
                </div>-->
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">样式设置：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_styleSet" lay-filter="type_styleSet">
                                <option value="styleEntry" selected="selected">样式对象</option>
                                <option value="functionCode">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_styleSet">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">成功回调：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_successCallBack" lay-filter="type_successCallBack">
                                <option value="functionCode" selected="selected">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_successCallBack">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">错误回调：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_errorCallBack" lay-filter="type_errorCallBack">
                                <option value="functionCode" selected="selected">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_errorCallBack">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">悬浮事件：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_pointerMove" lay-filter="type_pointerMove">
                                <option value="functionCode" selected="selected">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_pointerMove">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">悬浮样式：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_stylePointerMove" lay-filter="type_stylePointerMove">
                                <option value="functionCode"  selected="selected">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_stylePointerMove">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">点击事件：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_click" lay-filter="type_click">
                                <option value="functionCode" selected="selected">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_click">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">点击样式：</label>
                        <div class="layui-input-inline" style="width: 120px;">
                            <select name="type_styleClick" lay-filter="type_styleClick">
                                <option value="functionCode" selected="selected">函数体</option>
                                <option value="functionName">函数名</option>
                            </select>
                        </div>
                        <div class="layui-input-inline" style="width: 50px;margin-top: 5px">
                            <button class="layui-btn layui-btn-xs layui-btn-primary function" id="btn_styleClick">
                                <i class="layui-icon">&#xe654;</i>
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </c:when>
        <c:when test="${type == 'ol.layer.VectorTile'}">

        </c:when>
        <c:when test="${type == 'ol.layer.Heatmap'}">

        </c:when>
        <c:when test="${type == 'ol.layer.Heatmap'}">

        </c:when>
    </c:choose>
    <table id="sourcelist" class="layui-table" lay-filter="sourcelist"></table>
    <div class="layui-form-item" style="margin-top: 15px">
        <div class="layui-input-block" style="margin-left:80px">
            <button class="layui-btn" lay-submit="" id="sourcebind">提 交</button>
            <button id="refresh" class="layui-btn">刷新</button>
            <button type="reset" class="layui-btn">重 置</button>
        </div>
    </div>
</div>
<div class="layui-col-md9">
    <div id="map" style="margin:0 auto;width: 100%;height:100%;"></div>
</div>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/libs/layui2.2.5/layui.js"></script>
<script>
    var $,gis,layerName,
        //functionAttr={styleSet:{},pointerMove:{},stylePointerMove:{},click:{},styleClick:{}};
        functionAttr = ${options} != null?${options}:{
            styleSet:{},
            successCallBack:{},
            errorCallBack:{},
            pointerMove:{},
            stylePointerMove:{},
            click:{},
            styleClick:{}
        };

    function mapInit(layer,source) {
        var projection = (layer.hasOwnProperty("projection")
            && layer["projection"] != undefined
            && layer["projection"] != null
            && layer["projection"] != "")?layer["projection"]:"EPSG:4326",
            center;
        if(projection == "EPSG:3857"){
            center = [13221060.65120835, 4370248.148328505];
        }else {
            center = [118.360772748187, 36.13540951960175];
        }
        c3gis = new C3GIS({
            target:"map",
            center: center,
            zoom: 7,
//            minZoom:7,
//            maxZoom:19,
            projection: projection
        });
        if(source != undefined && source != null
            && (source["type"] === 'ol.supermap.FeatureService' || source["type"] === 'arcgis.FeatureService')){
            c3gis.addLayer(layer["type"],layer["layerName"],{source:source});
            //c3gis.setSourceForLayer_featureService(layer["layerName"],source["type"],source["options"]);
        }else {
            if(functionAttr.hasOwnProperty('successCallBack')
                && functionAttr.successCallBack.hasOwnProperty('code')
                && functionAttr.successCallBack.code != ''){
                source["options"]['successCallBack']
                    = eval("("+ functionAttr.successCallBack.code +")")
            }
            if(functionAttr.hasOwnProperty('errorCallBack')
                && functionAttr.errorCallBack.hasOwnProperty('code')
                && functionAttr.errorCallBack.code != ''){
                source["options"]['errorCallBack']
                    = eval("("+ functionAttr.errorCallBack.code +")")
            }

            c3gis.addLayer(layer["type"],layer["layerName"],{
                source:(source != undefined && source != null)?c3gis.createSourceByType(source["type"],source["options"]):null
            });
        }
        return c3gis
    }
    /**
     * 初始化右侧table
     */
    layui.use(['table','form', 'layer'], function () {
        var table = layui.table,
            form = layui.form,
            layer = layui.layer;
        var tableIns,sourceData,tableHight;
        $ = layui.jquery;

        if("${type}" == "ol.layer.Vector"){
            tableHight = '180px';
        }else {
            tableHight = '280px';
        }

        $.ajax({
            type:'get',
            url:'${pageContext.request.contextPath}/ol/layer/sourcelist?layerid=${layerId}',
            dataType: "json",
            contentType:'application/json;charset=utf-8',
            success:function(data) {
                sourceData = data;
                tableIns = table.render({
                    id: 'sourcelist',
                    elem: '#sourcelist'
//                        ,height: 'full-75'
                    ,height: tableHight
                    ,data:data
                    ,cols: [[
                        {checkbox: true}
                        ,{field: 'sourceName', align:'center', title: '数据源名称', width: 250}
                    ]]
                });
            },
            error: function (error){
                console.log(error);
            }
        });

        table.on('checkbox(sourcelist)', function(obj){
            var checkStatus = table.checkStatus('sourcelist');
            if(obj.type == "one" && obj.checked && sourceData.length > 0){
                for(var i = 0,len = sourceData.length;i < len;i++){
                    if(obj.data.sourceId != sourceData[i].sourceId){
                        sourceData[i].LAY_CHECKED = false;
                    }
                }
                tableIns.reload({data:sourceData});
            }
        });

        /**
         *  提交按钮绑定事件
         * */
        $("#sourcebind").click(function () {
            var checkStatus = table.checkStatus('sourcelist')
                ,checkData = checkStatus.data;
            if(checkStatus.isAll && checkData.length > 1){
                layer.msg('数据源不能多选', {icon: 5,anim: 6});
                return;
            }else if(checkData.length == 0){
                layer.msg('至少选择一条数据源', {icon: 5,anim: 6});
                return;
            }else {
                var bindData = {
                    layerId:'${layerId}',
                    sourceId:checkData[0].sourceId
                };
                if(functionAttr.styleSet.hasOwnProperty("code")
                    || functionAttr.pointerMove.hasOwnProperty("code")
                    || functionAttr.stylePointerMove.hasOwnProperty("code")
                    || functionAttr.click.hasOwnProperty("code")
                    || functionAttr.styleClick.hasOwnProperty("code")
                    || functionAttr.successCallBack.hasOwnProperty("code")
                    || functionAttr.errorCallBack.hasOwnProperty("code")){
                    bindData["options"] = functionAttr;
                }
                $.ajax({
                    type:'post',
                    url:'${pageContext.request.contextPath}/ol/layer/sourcebind',
                    dataType: "json",
                    contentType:'application/json;charset=utf-8',
                    data:JSON.stringify(bindData),
                    success:function(data) {
                        layer.msg(data.status);
                        window.parent.layIndex = null;
                        window.parent.closeAllLayer();
                    },
                    error: function (error){
                        console.log(error);
                    }
                });
            }
        });

        /**
         *  绑定刷新按钮事件
         * */
        $("#refresh").click(function () {
            var checkStatus = table.checkStatus('sourcelist')
                ,checkData = checkStatus.data;
            if(checkStatus.isAll && checkData.length > 1){
                layer.msg('数据源不能多选', {icon: 5,anim: 6});
                return;
            }else if(checkData.length == 0){
                layer.msg('至少选择一条数据源', {icon: 5,anim: 6});
                return;
            }
            $.ajax({
                type:'get',
                url:'${pageContext.request.contextPath}/ol/source/sourceentry?sourceid=' + checkData[0].sourceId,
                dataType: "json",
                success:function(data) {
                    if(data != null){
                        if(data['type'] != 'ol.supermap.FeatureService' && data['type'] != 'arcgis.FeatureService'){
                            if(functionAttr.hasOwnProperty('successCallBack') && functionAttr.successCallBack.hasOwnProperty("code")){
                                data["options"]['successCallBack'] = eval("("+ functionAttr.successCallBack.code +")");
                            }
                            if(functionAttr.hasOwnProperty('errorCallBack') && functionAttr.errorCallBack.hasOwnProperty("code")){
                                data["options"]['errorCallBack'] = eval("("+ functionAttr.errorCallBack.code +")");
                            }

                            var querySource = gis.createSourceByType(data["type"],data["options"]);
                            gis.setSourceForLayer(layerName,querySource);
                        }else {
                            gis.setSourceForLayer_featureService(layerName,data['type'],data['options']);
                        }
                        refreshVectorOptions(layerName);
                    }
                },
                error: function (error){
                    console.log(error);
                }
            });
        });

        /**
         * 绑定样式设置按钮事件
         * */
        $(".function").click(function (event) {
            var functionType = event.currentTarget.id.split("_")[1],
                typeSelect = $("select[name=type_"+ functionType +"]").val(),
                title,code = null;
            if(!functionAttr.hasOwnProperty(functionType)){
                functionAttr[functionType] = {};
            }
            if(functionAttr[functionType].hasOwnProperty("code")){
                code = functionAttr[functionType].code;
            }
            switch(typeSelect){
                case "styleEntry":
                    if(code == null){
                        code = "";
                    }
                    title = "请输入样式对象";
                    break;
                case "functionCode":
                    title = "请输入函数内容";
                    if(code == null || functionAttr[functionType].type != typeSelect){
                        if(functionType == "successCallBack"){
                            code = "function(data) {\n   // coding...\n}";
                        }else if(functionType == "errorCallBack"){
                            code = "function(error) {\n   // coding...\n}";
                        }else {
                            code = functionType.indexOf("style") == 0
                                ? "function(feature) {\n   // coding...\n}":"function(e) {\n   // coding...\n}";
                        }

                    }
                    break;
                case "functionName":
                    title = "函数名";
                    break;
            }


            if(typeSelect == 'functionName'){
                layer.prompt({
                    formType: 0,
                    title: title,
                    value:functionAttr[functionType].type == typeSelect?code:""
                },function(value, index){
                    if(value != null && value != ""){
                        functionAttr[functionType].type = typeSelect;
                        functionAttr[functionType].code = value;
                    }
                    layer.close(index);
                });
            }else{
                layer.prompt({
                    formType: 2,
                    title: title,
                    maxlength: 10000,
                    area: ['800px', '400px'],
                    value:code,
                }, function(value, index, elem){
                    if(value != null && value != ""){
                        functionAttr[functionType].type = typeSelect;
                        functionAttr[functionType].code = value;
                    }

                    layer.close(index);
                });
            }
            return false;
        });




        /**
         * 初始化地图
         */
        $.ajax({
            type:'get',
            url:'${pageContext.request.contextPath}/ol/layer/layerentry?layerid=${layerId}',
            dataType: "json",
            success:function(data) {
                if(data != null){
                    layerName = data["layer"]["layerName"];
                    gis = mapInit(data["layer"],data["source"]);
                    if(data["layer"]["type"] == "ol.layer.Vector"){
                        refreshVectorOptions(layerName);
                    }
                }
            },
            error: function (error){
                console.log(error);
            }
        });
    });

    function refreshVectorOptions(layerName) {
        var pointerMove = getInteractionInfo("pointerMove"),
            click = getInteractionInfo("click");
        //设置图层样式
        if(functionAttr.styleSet.hasOwnProperty("code")){
            layerStyle = eval("("+ functionAttr.styleSet.code +")");
            gis.setStyleForVectoryLayer(layerName,layerStyle);
        }

        //设置图层悬浮事件
        if(pointerMove.hasOwnProperty("style") || pointerMove.hasOwnProperty("callBack")){
            gis.addInteraction(layerName,"pointerMove",
                eval("("+ pointerMove.style +")"),
                eval("("+ pointerMove.callBack +")")
            );
        }

        //设置图层单击事件
        if(click.hasOwnProperty("style") || click.hasOwnProperty("callBack")){
            gis.addInteraction(layerName,"click",
                eval("("+ click.style +")"),
                eval("("+ click.callBack +")")
            );
        }
    }

    function getInteractionInfo(interactionType) {
        var layerStyle = null,interactionResult = {};

        //设置事件样式
        if(functionAttr[interactionType == "pointerMove"?"stylePointerMove":"styleClick"].hasOwnProperty("code")){
            interactionResult.style = functionAttr[interactionType == "pointerMove"?"stylePointerMove":"styleClick"].code;
        }

        //设置事件回调函数
        if(functionAttr[interactionType].hasOwnProperty("code")){
            interactionResult.callBack = functionAttr[interactionType].code;
        }

        //设置回调函数则必须设置事件样式，默认是图层的样式
        if(interactionResult.hasOwnProperty("callBack")
            && !interactionResult.hasOwnProperty("style")
            && functionAttr.styleSet.hasOwnProperty("code")){
            interactionResult.style = functionAttr.styleSet.code;
        }

        return interactionResult;
    }
</script>
</body>
</html>
